package cn.itheima.server_response;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

//.使用响应下载图片
    @WebServlet("/ServletTest6")
    public class ServletTest6 extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            //获取文件的绝对路径
            String realpath = getServletContext().getRealPath("/1.png");
            System.out.println(realpath);

            //创建字节输入流对象 关联读取的文件
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realpath));
            //设置响应头的类型 应用支持的类型为字节流
            response.setHeader("Content-Type", "application/octet-stream");
            //获取字节输出流对象
            ServletOutputStream sos = response.getOutputStream();

            //循环读写文件
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1) {
                sos.write(bytes, 0, len);
            }
            bis.close();
            sos.close();
        }

        @Override
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doGet(request, response);
        }
    }
